import { Component } from 'react';

import StandardTable from '@/components/StandardTable';
import styles from './index.less';

export class CommonLogs extends Component {
  constructor() {
    super();
  }

  state = {
    tableData: {
      list: [],
      pagination: {},
    },
  };

  columns = () => [
    {
      title: '操作时间',
      dataIndex: 'date',
      className: styles.date,
      render: this.renderTableSpan,
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      render: this.renderTableSpan,
    },
    {
      title: '来源',
      dataIndex: 'sourceType',
      render: this.renderTableSpan,
    },
    {
      title: '日志',
      children: [
        {
          title: '操作',
          dataIndex: 'actionName',
        },
        {
          title: '结果',
          dataIndex: 'result',
          render: text => {
            const resultStr = text ? '成功' : '失败';
            return <div dangerouslySetInnerHTML={{ __html: resultStr || '-' }} />;
          },
        },
        {
          title: '详情',
          dataIndex: 'message',
          render: text => {
            return <div dangerouslySetInnerHTML={{ __html: text || '-' }} />;
          },
        },
      ],
    },
  ];

  renderTableSpan(text, row) {
    return {
      children: <div>{text}</div>,
      props: {
        rowSpan: row.date ? row.length : 0,
      },
    };
  }

  queryOperationLog({ pageIndex = 1, pageSize = 50 } = {}) {
    const {
      dispatch,
      location: { query },
    } = this.props;
    dispatch({
      type: this.action,
      payload: {
        queryParams: {
          pageIndex,
          pageSize,
          id: query[this.idName],
        },
      },
    }).then(({ errorCode, data, pagination }) => {
      if (errorCode === 0) {
        const newLogs = data.reduce((total, item, index) => {
          item.operateLogs[0] = {
            ...item.operateLogs[0],
            date: item.date,
            operator: item.operator,
            sourceType: item.sourceType,
            length: item.operateLogs.length,
          };
          return [...total, ...item.operateLogs];
        }, []);
        this.setState({
          tableData: {
            list: newLogs,
            pagination,
          },
        });
      }
    });
  }

  handleChange = (pagination) => {
    let params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize
    };
    this.queryOperationLog(params);
  }

  renderTable = loading => {
    const { tableData } = this.state;
    return (
      <StandardTable
        tableLayout="fixed"
        rowKey="id"
        bordered={true}
        loading={loading}
        data={tableData}
        columns={this.columns()}
        onChange={this.handleChange}
      />
    );
  };
}
